package com.csweimei.rentmanagementtreasure.enterprise.viewModel;

import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.csweimei.rentmanagementtreasure.WebActivity;
import com.csweimei.rentmanagementtreasure.base.AppConfig;
import com.csweimei.rentmanagementtreasure.enterprise.act.BuyCodeActivity;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.OdBean;
import com.csweimei.rentmanagementtreasure.http.entity.VipBean;
import com.csweimei.rentmanagementtreasure.http.entity.WXBean;
import com.csweimei.rentmanagementtreasure.pop.PopBean;
import com.csweimei.rentmanagementtreasure.pop.PopBuy;
import com.csweimei.rentmanagementtreasure.pop.PopInput;
import com.csweimei.rentmanagementtreasure.pop.PopSelClick;
import com.csweimei.rentmanagementtreasure.pop.PopUtils;
import com.csweimei.rentmanagementtreasure.utils.PayUtil;
import com.csweimei.rentmanagementtreasure.utils.UserUtils;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.csyuejia.paylib.PayUtils;
import com.csyuejia.paylib.alipay.Alipay;
import com.csyuejia.paylib.wxpay.WXPay;
import com.gtdev5.geetolsdk.mylibrary.beans.Gds;
import com.gtdev5.geetolsdk.mylibrary.beans.UpdateBean;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.contants.API;
import com.gtdev5.geetolsdk.mylibrary.contants.Contants;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DataSaveUtils;
import com.gtdev5.geetolsdk.mylibrary.util.MapUtils;
import com.gtdev5.geetolsdk.mylibrary.util.SpUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;

public class VipVM extends TitleVM {

    public ObservableField<Integer> entVipID = new ObservableField<>();
    public ObservableField<String> entPrice = new ObservableField<>();
    public ObservableField<String> odPrice = new ObservableField<>();
    public ObservableField<String> vip1 = new ObservableField<>();

    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //开关观察者
        public SingleLiveEvent<Boolean> check = new SingleLiveEvent<>();
    }

    public BindingCommand checkOnClickCommand = new BindingCommand(() -> {
        //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
        uc.check.setValue(uc.check.getValue() == null || !uc.check.getValue());
    });


    public BindingCommand vipxy = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putString("flag", "VIP");
            startActivity(WebActivity.class, bundle);
        }
    });

    public VipVM(@NonNull Application application, BaseModel model) {
        super(application, model);
        setTitleText("企业服务");
        setTitleTextColor("white");
        setRightText("兑换席位码");
    }


    @Override
    public void onCreate() {
        super.onCreate();
        UpdateBean updateBean = DataSaveUtils.getInstance().getUpdate();
        for (Gds gds :updateBean.getGds()) {
            if (gds.getName().equals("企业会员")){
                entVipID.set(gds.getGid());
                entPrice.set("¥"+gds.getPrice());
                odPrice.set(gds.getPrice());
            }
        }
    }

    public BindingCommand buyCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (uc.check.getValue() == null) {
                ToastUtils.showShort("请阅读并同意《会员用户协议》");
            } else {
                if (uc.check.getValue()) {
                    startActivity(BuyCodeActivity.class);
                } else {
                    ToastUtils.showShort("请阅读并同意《会员用户协议》");
                }
            }
        }
    });

    int payWay = 2;

    public BindingCommand buy = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (uc.check.getValue() == null) {
                ToastUtils.showShort("请阅读并同意《会员用户协议》");
            } else {
                if (uc.check.getValue()) {
                    PopBuy popBuy = new PopBuy(mActivity, new PopSelClick() {
                        @Override
                        public void sel(PopBean x) {
                            payWay = Integer.parseInt(x.getName());
//                            switch (x.getName()){
//                                case "1":
//                                    payWx();
//                                    break;
//                                case "2":
//                                    payZfb();
//                                    break;
//                            }
                            Map<String,String> map = MapUtils.getOrder(1, entVipID.get(), Float.parseFloat(odPrice.get()), payWay);
                            map.put("num","");
                            HttpUtils.getInstance().post( SpUtils.getInstance().getString(Contants.COMMON_URL, API.COMMON_URL) + "order.od_zgb",
                                    map, new BaseCallback<OdBean>() {
                                @Override
                                public void onRequestBefore() {

                                }

                                @Override
                                public void onFailure(Request request, Exception e) {

                                }

                                @Override
                                public void onSuccess(Response response, OdBean odResultBean) {
                                    if (odResultBean.isIssucc()){
                                        ToastUtils.showShort("支付中");
                                        if (payWay == 1) {
                                            payWx(odResultBean);
                                        }else if (payWay == 2) {
                                            payAli(odResultBean);
                                        }
                                    }else {
                                        ToastUtils.showShort(odResultBean.getMsg());
                                    }

                                }

                                @Override
                                public void onError(Response response, int errorCode, Exception e) {

                                }
                            });

                        }
                    });
                    PopUtils.showPop(mActivity,popBuy,false);
                } else {
                    ToastUtils.showShort("请阅读并同意《会员用户协议》");
                }
            }
        }
    });

    private void payWx(OdBean o) {
        String payParam = PayUtils.getJson(
                new String[]{"appid", "partnerid", "prepayid", "package", "noncestr", "timestamp", "sign"},
                new String[]{
                        o.getAppid(),
                        o.getPartnerId(),
                        o.getPrepayid(),
                        o.getPackageStr(),
                        o.getNonceStr(),
                        o.getTimestramp(),
                        o.getSign()});
        WXPay.init(mActivity, o.getAppid());      // 要在支付前调用

        WXPay.getInstance().doPay(payParam, new WXPay.WXPayResultCallBack() {
            @Override
            public void onSuccess() {
                ToastUtils.showShort("支付成功");
                GTUpdate();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        break;
                    case WXPay.ERROR_PAY_PARAM:
                        break;
                    case WXPay.ERROR_PAY:
                        break;
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showShort("支付取消");
            }
        });
    }

    private void payWx() {
        Map<String,String>map = new HashMap<>();
        map.put("client_id",AppConfig.getDeviceId((Context) getLifecycleProvider()));
        map.put("userid",model.getLoginInfo().getData().getUser_id());
        map.put("appname",AppConfig.APP_NAME);
        map.put("price",odPrice.get());
        map.put("phone_type","Android");
        map.put("commodity","购买企业服务");
        map.put("typeid","1");
        map.put("codenum","0");

        model.WeChetPay(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<WXBean>() {
                    @Override
                    public void onNext(WXBean o) {
                        if (o.code == 1) {
                            long timestamp = System.currentTimeMillis();
                            String nonceStr = PayUtil.genNonceStr();
                            String packageSign = "Sign=WXPay";

                            Map<String, String> map = new LinkedHashMap<>();
                            map.put("appid", AppConfig.WXAPPID);
                            map.put("noncestr", nonceStr);
                            map.put("package", packageSign);
                            map.put("partnerid", AppConfig.WXPARTNER_ID);
                            map.put("prepayid", o.prepay_id);
                            map.put("timestamp", timestamp + "");

                            String sign = PayUtil.genAppSign(map, AppConfig.WXAPIKEY);

                            String payParam = ValidateUtils.getJson(
                                    new String[]{"appid", "partnerid", "prepayid", "package", "noncestr", "timestamp", "sign"},
                                    new String[]{
                                            AppConfig.WXAPPID,
                                            AppConfig.WXPARTNER_ID,
                                            o.prepay_id,
                                            packageSign,
                                            nonceStr,
                                            String.valueOf(timestamp),
                                            sign});
                            WXPay.init((Context) getLifecycleProvider(), AppConfig.WXAPPID);      // 要在支付前调用

                            WXPay.getInstance().doPay(payParam, new WXPay.WXPayResultCallBack() {
                                @Override
                                public void onSuccess() {

                                }

                                @Override
                                public void onError(int error_code) {

                                    switch (error_code) {
                                        case WXPay.NO_OR_LOW_WX:
                                            break;

                                        case WXPay.ERROR_PAY_PARAM:
                                            break;

                                        case WXPay.ERROR_PAY:
                                            break;
                                    }
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        } else {
                            ToastUtils.showShort(o.msg);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void payAli(OdBean o) {
        new Alipay(mActivity, o.getPackageStr(), new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                GTUpdate();
            }

            @Override
            public void onDealing() {
                ToastUtils.showShort("支付处理中...");

            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        ToastUtils.showShort("支付失败:支付结果解析错误");
                        break;
                    case Alipay.ERROR_NETWORK:
                        ToastUtils.showShort("支付失败:网络连接错误");
                        break;
                    case Alipay.ERROR_PAY:
                        ToastUtils.showShort("支付错误:支付宝支付失败");
                        break;
                    default:
                        ToastUtils.showShort("支付错误");
                        break;
                }

            }

            @Override
            public void onCancel() {
                ToastUtils.showShort("支付取消");

            }
        }).doPay();
    }

    private void GTUpdate() {
        HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {
            }

            @Override
            public void onSuccess(Response response, UpdateBean updateBean) {
                if (updateBean.getIssucc()) {
                    if (updateBean != null) {
                        DataSaveUtils.getInstance().saveAppData(updateBean);
                        UserUtils.setVip(updateBean.getVip());
                        if (DataSaveUtils.getInstance().isVip()){
                            onResume();
//                            viewModel.vipTime.set("会员到期时间："+DataSaveUtils.getInstance().getVip().getTime());
                        }
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

    @Override
    protected void rightTextOnClick(String s) {
        super.rightTextOnClick(s);
        PopInput popInput = new PopInput(mActivity, new PopSelClick() {
            @Override
            public void sel(PopBean x) {
                useCode(x.getName());
            }
        });
        popInput.setTitle("填写兑换码");
        PopUtils.showPop(mActivity,popInput,false);
    }

    private void useCode(String name) {
        Map<String,String> map = AppConfig.getCurMap(model);
        map.put("code",name);
        model.usecode(map)
                .compose(RxUtils.exceptionTransformer())
                .compose(RxUtils.schedulersTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult o) {
                        ToastUtils.showShort(o.msg);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        getVipInfo();
    }

    private void getVipInfo() {
        model.seach_vip(AppConfig.getCurMap(model))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<VipBean>() {
                    @Override
                    public void onNext(VipBean o) {
                        if (o.issucc){
                            if (o.getData().getCompanyDay() != 0){
                                AppConfig.setVipEnt(o.getData().getCompanyDay());
                                vip1.set(ValidateUtils.getTimeByType(o.getData().getCompanyEtime(),ValidateUtils.TIME_YMD)+"到期");
                            }else {
                                vip1.set("开通产品服务享受更多功能");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
